
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

export const PAGE = {
  miniPage: true,
  elPageMiniProps: {
    'pager-count': 5,
    'page-sizes': [10, 50, 100, 500],
    layout: 'sizes, prev, pager, next',
  },
}

// ============================== 导出混合 ============================== //

export default {
  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [CORE.mixWeb(), CORE.mixInfo()],

  /**
   * 状态数据 (函数返回对象)
   */
  data() {
    return {
      model: {}, // 双向绑定对象
    }
  },

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 表格属性
     */
    tableProps() {
      const { info: { idKey, height } } = this
      return {
        ...PAGE,
        idKey,
        auto: false,
        height,
      }
    },
  },

  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听所属对象
     */
    'info.obj': {
      deep: true,
      immediate: true,
      handler() {
        if (this.isDiff()) this.setModel()
      },
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 过滤查询
     */
    toSearch() {
      this.setList()
      this.startList()
    },

    /**
     * 点击复选
     */
    toSelect(idList) {
      const { list, info } = this
      const { obj, bind, idKey } = info

      const id = idList.pop()
      const matched = list.find((item) => item[idKey] === id)
      const chosen = this.transChosen(matched || {})

      this.param.idList = id ? [id] : []

      this.model = chosen

      this.$set(obj, bind, chosen)
      this.$emit('change', chosen)
    },

    /**
     * 转换选中项
     */
    transChosen(chosen) {
      return chosen
    },

    /**
     * 是否不等 (可覆盖)
     */
    isDiff() {
      const { info, model } = this
      const { obj, bind, idKey } = info
      const value = obj[bind]
      if (!CORE.isJSON(value)) return model[idKey]

      return value[idKey] !== model[idKey]
    },

    /**
     * 设置内部绑定值 (可覆盖)
     */
    setModel() {
      const { obj, bind, idKey } = this.info
      this.model = CORE.isJSON(obj[bind]) ? obj[bind] : {}

      const id = this.model[idKey]
      this.param.idList = id ? [id] : []
    },
  },
}
